<template>
  <van-form @submit="onSubmit">
    <!-- 标签特殊处理 -->
    <template v-if="editUser.editKey === 'tags'">
      <van-field
        v-model="tagsInput"
        name="tags"
        label="标签"
        placeholder="请输入标签，多个标签用逗号分隔"
      />
    </template>
    <!-- 性别特殊处理 -->
    <template v-else-if="editUser.editKey === 'gender'">
      <van-field
        name="gender"
        label="性别"
      >
        <template #input>
          <van-radio-group v-model="genderValue" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </template>
    <!-- 默认字段 -->
    <template v-else>
      <van-field
        v-model="editUser.currentValue as string"
        :name="editUser.editKey as string"
        :label="editUser.editName as string"
        :placeholder="`请输入${editUser.editName}`"
      />
    </template>
    
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        确认修改
      </van-button>
    </div>
  </van-form>

</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref, onMounted} from "vue";
import myAxios from "../../plugins/myAxios.ts";
import {showSuccessToast, showToast} from "vant";
import {getCurrentUser, updateCurrentUser} from "../../services/user.ts";

const router = useRouter();

const route = useRoute();
const editUser = ref({
  editKey: route.query.editKey,
  editName: route.query.editName,
  currentValue: route.query.currentValue
})

// 标签输入处理
const tagsInput = ref('');
// 性别选择
const genderValue = ref<number>(1);

// 初始化特殊字段
onMounted(() => {
  // 初始化标签输入
  if (editUser.value.editKey === 'tags' && editUser.value.currentValue) {
    try {
      const tags = JSON.parse(editUser.value.currentValue as string);
      tagsInput.value = tags.join(',');
    } catch (e) {
      console.error('解析标签失败', e);
      tagsInput.value = '';
    }
  }
  
  // 初始化性别选择
  if (editUser.value.editKey === 'gender' && editUser.value.currentValue) {
    const genderVal = Number(editUser.value.currentValue);
    genderValue.value = isNaN(genderVal) ? 1 : genderVal;
  }
});

const onSubmit = async () => {
  try {
    const userResponse = await getCurrentUser();
    if (userResponse?.code !== 0 || !userResponse?.data) {
      showToast('用户未登录或获取用户信息失败');
      return;
    }

    const loginUser = userResponse.data;

    // 构建更新数据
    let updateValue: any = editUser.value.currentValue;
    
    // 特殊字段处理
    if (editUser.value.editKey === 'tags') {
      // 处理标签：从逗号分隔的字符串转为数组
      const tagArray = tagsInput.value
        .split(',')
        .map(tag => tag.trim())
        .filter(tag => tag); // 过滤掉空标签
      
      updateValue = tagArray;
    } else if (editUser.value.editKey === 'gender') {
      // 使用radio选择的值
      updateValue = genderValue.value;
    }
    
    const updateData = {
      id: loginUser.id,
      [editUser.value.editKey as string]: updateValue,
    };

    console.log('提交更新数据:', updateData);

    const res = await myAxios.post('/user/update', updateData);
    console.log('更新响应:', res);

    if (res?.code === 0) {
      // 更新成功，更新本地用户状态
      const updatedUser = {...loginUser};
      updatedUser[editUser.value.editKey as string] = updateValue;
      
      // 确保更新localStorage和sessionStorage中的用户信息
      updateCurrentUser(updatedUser);
      
      // 清除可能的缓存
      localStorage.removeItem('tempUserData');
      
      showSuccessToast('修改成功');
      
      // 返回用户更新页面，并携带参数指示需要刷新
      router.push('/user/update?refresh=true&t=' + new Date().getTime());
    } else {
      // 使用showToast显示错误信息
      showToast(res?.message || '修改失败');
    }
  } catch (error) {
    console.error('更新用户信息出错:', error);
    showToast('更新用户信息时发生错误，请稍后重试');
  }
};

</script>

<style scoped>
.van-radio {
  margin-right: 20px;
}
</style>

